import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';

import 'package:provider/provider.dart';
import '../../../lib_basemodel/chat_room/kh_chat_room_enter_model.dart';
import '../../../lib_baseview/root_page.dart';
import '../../m_chatroom.dart';
import '../hall/room_main/chat_room_main_page.dart';
import 'room_page_model.dart';

class RoomPage extends StatefulWidget {
  static const routeName = '/room';

  // /// 房间id
  final String roomNo;

  /// 房间模型
  final KHChatRoomEnterModel? roomEnterModel;

  // final JoinSource? joinSource;
  final int? followUid;

  const RoomPage({
    super.key,
    required this.roomNo,
    // this.joinSource,
    this.roomEnterModel,
    this.followUid,
  });

  static Future show(
    BuildContext context,
    String roomNo, {
    int? type,
    int? expJoyride,
    // JoinSource? joinSource,
    int? followUid,
  }) async {
    if (roomNo.isEmpty) return;

    RootProxyModel roomModel = context.read<RootProxyModel>();

    if (roomModel.inRoom &&
        roomNo != roomModel.roomEnterModel?.chatRoomModel?.roomInfo?.roomNo) {
      // if (roomModel.inRoom && roomNo != roomModel.roomChannel) {
      // 用户在麦上，弹窗退房提示
      // if (roomModel.isOnMicSeat) {
      //   var shouldEnterRoom = await JRDialog.showCommonDialog(
      //     context: Get.context!,
      //     data: TextWithHorizontalBtnDialogData(
      //       title: T.current!.enter_room,
      //       desc: T.current!.enter_other_room_tips,
      //     ),
      //   );
      //   if (shouldEnterRoom != true) return;
      // }
      await roomModel.release();
    }

    // if (type != null) {
    //   RootProxyModel.instance?.doufengType = type;
    // }

    await _pushRoomPage(
      Get.context!,
      roomNo,
      type: type,
      // joinSource: joinSource,
      followUid: followUid,
    );
  }

  static Future _pushRoomPage(
    BuildContext context,
    String roomNo, {
    int? type,
    // JoinSource? joinSource,
    int? followUid,
  }) async {
    pop();

    await Navigator.of(Get.context!).push(
      MaterialPageRoute(
        builder: (context) => RoomPage(
          roomNo: roomNo,
          // joinSource: joinSource,
          followUid: followUid,
        ),
        settings: RouteSettings(name: routeName),
      ),
    );
  }

  /// pop[routeName]页面上的所有页面，[include]是否pop [routeName]页
  static void _popRoute(BuildContext context, String routeName, bool include) {
    bool find = false;
    Navigator.of(context).popUntil(
      (route) {
        if (route.isFirst) return true;

        bool temp = route.settings.name?.startsWith(routeName) ?? false;
        bool result = include ? find : temp;
        if (temp) find = true;
        return result;
      },
    );
  }

  static bool get exist => appNavigatorObserver.history.contains(routeName);

  static void pop() {
    if (!exist) return;

    _popRoute(Get.context!, routeName, true);
  }

  @override
  State<RoomPage> createState() => _RoomPageState();
}

class _RoomPageState extends State<RoomPage> {
  // JoinChannelRsp? joinChannelRsp;

  late RootProxyModel rootModel;

  @override
  void initState() {
    super.initState();

    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarBrightness: Brightness.dark,
    ));

    rootModel = context.read<RootProxyModel>();
    rootModel.hideOverlay();

    load();
  }

  void load() {
    /// 这里记得要判断是否是在房间中，如果在房间中（点击小窗进入房间，就不用请求房间基础数据了）
    /// 这里为了简单，每次都请求房间数据

    // if ((rootModel.channel?.channelId.toInt() ?? 0) > 0 &&
    //     (rootModel.channel?.channelId.toInt() ?? 0) == widget.rid) {
    //   // 进入小窗中的房间，不再请求接口
    //   joinChannelRsp = JoinChannelRsp()
    //     ..channel = rootModel.channel!
    //     ..token = rootModel.token!
    //     ..wsUrl = rootModel.wsUrl!
    //     ..rtmToken = rootModel.rtmToken!;
    //   if (mounted) setState(() {});
    // } else {
    loadData(
      widget.roomNo,
      '',
      // joinSource: widget.joinSource,
      followUid: widget.followUid,
    );
    // }
  }

  Future loadData(
    String rid,
    String pwd, {
    int? type,
    // JoinSource? joinSource,
    int? followUid,
  }) async {
    /// 请求房间四大接口

    // JoinChannelReq req = JoinChannelReq();
    // req.channelId = $fixnum.Int64(rid);
    // req.password = pwd;
    // if (joinSource != null) {
    //   req.joinSource = joinSource;
    // }
    // if (followUid != null) {
    //   req.followUid = $fixnum.Int64(followUid);
    // }
    // var result = await RtcApi.instance.joinChannel(req);
    // if (result.isSuccess && (result.data?.channel.channelId.toInt() ?? 0) > 0) {
    //   joinChannelRsp = result.data;

    //   ///如果踩房用户在麦上 记录uid显示特定UI
    //   if (followUid != null) {
    //     for (SimpleChannelUserSlot element
    //         in joinChannelRsp?.channel.broadcaster ?? []) {
    //       if (element.user.id.toInt() == followUid) {
    //         rootModel.followUid = followUid;
    //         break;
    //       }
    //     }
    //   }
    //   if (mounted) setState(() {});
    // } else if (result.errorCode == 1001410210) {
    //   var result = await showNormalDialog(
    //       context: Get.context!,
    //       title: T.current!.room_locked,
    //       content: Column(
    //         mainAxisSize: MainAxisSize.min,
    //         children: [
    //           Text(
    //             T.current!.input_pwd_enter_room,
    //             style: TextStyle(
    //               fontSize: 16,
    //               fontWeight: FontWeight.w500,
    //               color: Color(0xff333333),
    //             ),
    //           ),
    //           const SizedBox(
    //             height: 10,
    //           ),
    //           FilledRoundedPinPut(onValueCompleted: (value) {
    //             pwd = value;
    //           }),
    //         ],
    //       ),
    //       showCancel: true,
    //       confirmText: T.current!.surer,
    //       onConfirm: () async {});

    //   if (result == true) {
    //     loadData(rid, pwd, joinSource: joinSource, followUid: followUid);
    //   } else {
    //     RoomPage.pop();
    //   }
    // } else {
    //   RoomPage.pop();
    //   showToast((result.errorMsg?.isNotEmpty ?? false)
    //       ? result.errorMsg!
    //       : T.current!.enter_room_fail);
    // }
  }

  Widget get mainPage {
    return MultiProvider(providers: [
      ChangeNotifierProxyProvider<RootProxyModel, RoomPageModel>(
        create: (context) => RoomPageModel()
          ..roomModel = rootModel
          ..initData(widget.roomNo),
        update: (context, rootModel, pageModel) =>
            pageModel!..roomModel = rootModel,
      ),
    ], child: const ChatRoomMainPage());
  }

  Widget get body => mainPage;

  Widget get loadingWidget => Container(
      decoration: const BoxDecoration(
        image: DecorationImage(
            fit: BoxFit.cover, image: AssetImage(RoomPageMixin.defaultBgAsset)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SafeArea(
            child: CupertinoButton(
              onPressed: () {
                Navigator.of(context).maybePop();
              },
              padding: EdgeInsets.zero,
              child: Container(
                width: 40,
                height: 36,
                alignment: Alignment.centerLeft,
                child: Padding(
                  padding: const EdgeInsets.only(left: 20),
                  child: Image.asset(
                    "assets/images/chat_room_ic_back.png",
                    width: 11,
                    height: 20,
                    color: Colors.white,
                    fit: BoxFit.fill,
                  ),
                ),
              ),
            ),
          ),
          const Expanded(
              child: Center(
                  child: CupertinoActivityIndicator(
            color: Colors.white,
          ))),
        ],
      ));

  @override
  Widget build(BuildContext context) {
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: SystemUiOverlayStyle.light,
      child: body,
      // child: joinChannelRsp?.channel == null ? loadingWidget : body,
    );
  }
}
